<?php

namespace Admin\Controller;

use Think\Controller;

class WorkCertController extends CommonController
{

    function __construct()
    {
        parent::__construct();
    }
    /**
     * 工作认证列表 视图
     */
    public function work_cert_list()
    {
        $this->display();
    }

    /**
     * 工作认证列表
     */
    public function get_cert_list()
    {
        $type=I('type',0);
        $index=I('index');
        $n = I('page', 1);
        $num = 10;
        $page = ($n - 1) * $num;
        $where = [];
        if ($_SESSION['role_id'] ==2) {//客服看分配给自己的名单
            $where['a.out_kf_id'] = array('eq', $_SESSION['id']);
        }
        if($index=='2'){//预审不通过
            $where['a.status'] = 10;
        }else{
            $where['a.status'] = 9;
        }
//
        $field = "b.truename as user_name,b.mobile,b.id,b.ctime,b.vid,c.name as admin_name,a.ctime as sub_time";
        if($type=='1'){//已沟通
           //子查询去重  沟通有多条数据
            $sub_sql=M('work_cert_mark','','KEFU')->group('vid')->select(false);
            $count=M('anti_check_user','','KEFU')->table('('.$sub_sql.') d')->join('join dxd_kefu.anti_check_user a on a.vid=d.vid ')->where($where)->count();
            $data=M('anti_check_user', '', 'KEFU')->table('('.$sub_sql.') d')->join('join dxd_kefu.anti_check_user a on a.vid=d.vid ')->join('join dxd_user.user b on a.vid=b.vid')->join('dxd_kefu.admin c on a.out_kf_id=c.id')->where($where)->field($field)->limit($page, $num)->select();
       }else if($type=='2'){//未沟通
            $where['d.vid']=array('exp','is null');
            $count = M('anti_check_user', '', 'KEFU')->join('a left join dxd_kefu.work_cert_mark d on a.vid=d.vid')->where($where)->distinct('d.vid')->count();
            $data = M('anti_check_user', '', 'KEFU')->join('a join dxd_user.user b on a.vid=b.vid')->join('left join dxd_kefu.work_cert_mark d on a.vid=d.vid ')->join('join dxd_kefu.admin c on a.out_kf_id=c.id')->distinct('d.vid')->where($where)->field($field)->limit($page, $num)->select();
        }else{//待审核

            $count = M('anti_check_user', '', 'KEFU')->join('a join dxd_user.user b on a.vid=b.vid')->where($where)->count();
            $data = M('anti_check_user', '', 'KEFU')->join('a join dxd_user.user b on a.vid=b.vid')->join('dxd_kefu.admin c on a.out_kf_id=c.id')->where($where)->order('a.id asc')->field($field)->limit($page, $num)->select();
        }
        foreach ($data as $k => $v){
            $data[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            $data[$k]['sub_time'] = date('Y-m-d H:i:s', $v['sub_time']);
            if(empty($v['ctime'])){
                $data[$k]['ctime'] ="";
            }
            //备注数
            $data[$k]['mark_num'] = M('work_cert_mark', '', 'KEFU')->where(['type' => 1, 'vid' => $v['vid']])->count();
            $data[$k]['user_mobile'] = get_mobile($v['mobile']);
        }
        $count = intval($count);
        $tol = ceil($count / $num);
        $this->ajaxReturn(array('code' => '1001', 'tol' => $tol, 'count' => $count, 'result' => 'success', 'data' => $data));
    }

    /**
     * 工作认证详情
     */
    public function work_cert_detail()
    {
        $vid = I('vid');
        $phone = I('phone');
        $field = "a.content,a.ctime,b.name,a.admin_id";
        $cert_mark = M('work_cert_mark', '', 'KEFU')->join('a join dxd_kefu.admin b on a.admin_id=b.id')->where(['type' => 1, 'vid' => $vid])->order('a.ctime desc')->field($field)->select();
        foreach ($cert_mark as $k => $v) {
            $cert_mark[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
        }
//        $data=M('user_woke_verify','','USER')->where(['vid'=>$vid])->field('work_mobile,work_address,work_position,work_company,img_one,img_thr,img_two,monthly_income,ctime')->find();
        $work_pic = M('user_woke_verify', '', 'USER')->where(['vid' => $vid])->field('work_company,img_one,img_thr,img_two')->find();
        $user = M('user', '', 'USER')->where(['vid' => $vid])->getField('truename');
        $where = [];
        $where['vid'] = $vid;
        $task_time=M('anti_check_user', '', 'KEFU')->where($where)->getfield('ctime');
        if(empty($task_time)){
            $data['task_time']="";
            $data['warn']="";
        }else {
            $data['task_time'] = date('Y-m-d H:i:s', $task_time);
            $past=date('Y-m-d',$task_time);
            $now=date('Y-m-d',time());
            $date= $this->DiffDate($past,$now);

            $time = time();
            $day = floor(abs(($time - $task_time) / (24 * 3600)));
            $hour = floor(abs(($time - $task_time) - ($day * 24 * 3600)) / 3600);
            if ($time > $task_time) {
                $data['warn'] = '任务超时' . $date. $hour . '小时';
            } else {
                $data['warn'] = '距离任务还有' .$date. $hour . '小时';
            }
        }

        //渠道商
        $channel=M('user','','USER')->join('a join dxd_cpa.channel_merchant b on a.channel=b.channel_num')->where(['a.vid'=>$vid])->getField('b.name');
        $this->assign(
            array('phone' => $phone,
            'data'=>$data,
            'vid' => $vid,
            'channel' => $channel,
            'user_name' => $user,
            'cert_mark' => $cert_mark,
            'work_pic' => $work_pic));
        $this->display();
    }

    /**
     * 工作认证 任务备注提交
     */
    public function cert_mark()
    {
        $vid = I('vid');
        $content = I('content');
        $arr = array('vid' => $vid, 'admin_id' => $_SESSION['id'], 'content' => $content, 'ctime' => time(), 'type' => 1);
        $add = M('work_cert_mark', '', 'KEFU')->add($arr);
        if ($add) {
            $this->ajaxReturn(['code' => '1001', 'result' => '备注成功！']);
            add_log("工作认证备注提交".$vid);
        } else {
            $this->ajaxReturn(['code' => '1002', 'result' => '备注失败！']);
        }
    }
    /**
     * 工作认证 任务备注提交
     */
    public function cert_result()
    {
        $vid = I('vid');
        $type = I('type');//1 不通过 2 通过  不通过则打电话叫用户重新提交，否则进入反欺诈流程
        //添加事物
        M('user', '', 'USER')->startTrans();
        M('anti_check_user', '', 'KEFU')->startTrans();
        M('tmp_user', '', 'KEFU')->startTrans();

        if ($type == 1) {
            $arr=array('kf_check_time'=>time(),'status'=>10);
            $update1 = M('anti_check_user', '', 'KEFU')->where(['vid' => $vid])->save($arr);
            $update2 = M('tmp_user', '', 'KEFU')->where(['vid' => $vid])->setField('status', 1);
            if ( $update1 && $update2) {
                M('user', '', 'USER')->commit();
                M('anti_check_user', '', 'KEFU')->commit();
                M('tmp_user', '', 'KEFU')->commit();
                $this->ajaxReturn(['code' => '1001', 'result' => '成功！']);
            } else {
                M('user', '', 'USER')->rollback();
                M('anti_check_user', '', 'KEFU')->rollback();
                M('tmp_user', '', 'KEFU')->rollback();

                $this->ajaxReturn(['code' => '1002', 'result' => '失败！']);
            }
          add_log('审核用户工作认证不通过');
        } else if ($type == 2) {
            $arr=array('kf_check_time'=>time(),'status'=>11);
            $update1 = M('anti_check_user', '', 'KEFU')->where(['vid' => $vid])->save($arr);
            $update2 = M('tmp_user', '', 'KEFU')->where(['vid' => $vid])->setField('status', 1);
            if ($update1 && $update2) {
                M('anti_check_user', '', 'KEFU')->commit();
                M('tmp_user', '', 'KEFU')->commit();
                $this->ajaxReturn(['code' => '1001', 'result' => '成功！']);
            } else {
                M('anti_check_user', '', 'KEFU')->rollback();
                M('tmp_user', '', 'KEFU')->rollback();
                $this->ajaxReturn(['code' => '1002', 'result' => '失败！']);
            }
          add_log('审核用户工作认证通过');
        }
    }

    //工作认证
    public function work_cert(){
        $vid=I('vid');
        $data=M('user_woke_verify','','USER')->where(['vid'=>$vid])->field('work_mobile,work_address,work_position,work_company,img_one,img_thr,img_two,monthly_income,ctime')->find();
        //渠道商
        $channel=M('user','','USER')->join('a join dxd_cpa.channel_merchant b on a.channel=b.channel_num')->where(['a.vid'=>$vid])->getField('b.name');

        $this->assign(array(
            'data'=>$data,
            'channel'=>$channel,
            'vid'=>$vid
        ));
        $this->display();
    }

    //工作图片修改
    public function work_pic_save()
    {
        $work1 = I('img_one');
        $work2 = I('img_two');
        $work3 = I('img_thr');
        $vid = I('vid');
        $path = 'Public/';
        $url = 'http://gxxj.oss-cn-hangzhou.aliyuncs.com';
        $success = new \Service\OssClient('LTAI6sZcsEa0SGHc', '053o9lXKyeLh1J1nmlykMg0z8N0Q5E', $url);
        $user_work_verify=M('user_woke_verify','','USER');
        $user_work_verify->startTrans();
         if($work1!='no'){
            $new_file = $this->base64_to_image($work1, $path);
            $image['name'] = $new_file;
            $ext = strtolower(trim(substr($image['name'], strrpos($image['name'], '.')), '.'));
            $image['name'] = md5(time() . uniqid());
            $object = 'adm/' . $image['name'] . '.' . $ext;
            try {
                $success->uploadFile('gxxj', $object, $new_file);
                $res = $url . '/adm/' . $image['name'] . '.' . $ext;
            } catch (Exception $e) {

            }
            if ($res == '1002') {
                $data['result'] = '图片不得大于2M';
                echo json_encode(array('code' => '1002', 'result' => '图片不得大于2M'));
                die;
            } else {
                $update=$user_work_verify->where(['vid'=>$vid])->setField('img_one',$res);
            }
            unlink($new_file);
        }
         if($work2!='no'){
            $new_file = $this->base64_to_image($work2, $path);
            $image['name'] = $new_file;
            $ext = strtolower(trim(substr($image['name'], strrpos($image['name'], '.')), '.'));
            $image['name'] = md5(time() . uniqid());
            $object = 'adm/' . $image['name'] . '.' . $ext;
            try {
                $success->uploadFile('gxxj', $object, $new_file);
                $res = $url . '/adm/' . $image['name'] . '.' . $ext;
            } catch (Exception $e) {

            }
            if ($res == '1002') {
                $data['result'] = '图片不得大于2M';
                echo json_encode(array('code' => '1002', 'result' => '图片不得大于2M'));
                die;
            } else {
                $update=$user_work_verify->where(['vid'=>$vid])->setField('img_two',$res);
            }
             unlink($new_file);
        }

         if($work3!='no'){
            $new_file = $this->base64_to_image($work3, $path);
            $image['name'] = $new_file;
            $ext = strtolower(trim(substr($image['name'], strrpos($image['name'], '.')), '.'));
            $image['name'] = md5(time() . uniqid());
            $object = 'adm/' . $image['name'] . '.' . $ext;
            try {
                $success->uploadFile('gxxj', $object, $new_file);
                $res = $url . '/adm/' . $image['name'] . '.' . $ext;
            } catch (Exception $e) {

            }
            if ($res == '1002') {
                $data['result'] = '图片不得大于2M';
                echo json_encode(array('code' => '1002', 'result' => '图片不得大于2M'));
                die;
            } else {
                $update=$user_work_verify->where(['vid'=>$vid])->setField('img_thr',$res);
            }
             unlink($new_file);
        }
        if($update){
//            $cert_status= M('user','','USER')->where(['vid'=>$vid])->getField('cert_status');
//             if($cert_status!=2 && $cert_status!=3){
//                 $arr=array('status'=>11,'fk_status'=>0);
//                 $update_1=M('anti_check_user','','KEFU')->where(['vid'=>$vid])->save($arr);
//                $update_2= M('tmp_user','','KEFU')->where(['vid'=>$vid])->setField('status',1);
//                 if ($update_1 && $update_2){
//                     $user_work_verify->commit();
//                 }else{
//                     $user_work_verify->rollback();
//                 }
//             }else{
//                 $user_work_verify->rollback();
//                 echo json_encode(array('code' => '1002', 'result' => '用户已出审核结果'));
//                 die;
//             }
//             add_log('修改用户照片，用户进入反欺诈');

             //转交到预审
            $user_work_verify->commit();
            add_log("修改用户工作图片".$vid);
            echo json_encode(array('code' => '1001', 'result' => '上传成功'));
            die;
        }else{
            $user_work_verify->rollback();
            echo json_encode(array('code' => '1002', 'result' => '上传失败'));
            die;
        }
    }

    public function base64_to_image($base64, $path)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
            $type = $result[2];
            $new_file = $path . time() . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)))) {
                return $new_file;
            } else {
                return false;
            }
        }
    }

    public function work_save(){
         $work_mobile=I('work_mobile');
         $work_address=I('work_address');
         $work_position=I('work_position');
         $work_company=I('work_company');
         $monthly_income=I('monthly_income');
         $vid=I('vid');
         $arr=array('work_mobile'=>$work_mobile,'work_address'=>$work_address,'work_position'=>$work_position,'work_company'=>$work_company,'monthly_income'=>$monthly_income);
         $update=M('user_woke_verify','','USER')->where(['vid'=>$vid])->save($arr);
         if($update){
             add_log("修改用户工作认证信息".$vid);
             $this->ajaxReturn(array('code'=>'1001','result'=>'修改成功'));
             die;
         }
        $this->ajaxReturn(array('code'=>'1002','result'=>'修改失败'));
        die;
    }
    //年月日转换
    function DiffDate($date1,$date2) {
        if (strtotime($date1) > strtotime($date2)) {
            $ymd = $date2;
            $date2 = $date1;
            $date1 = $ymd;
        }
        list($y1, $m1, $d1) = explode('-', $date1);
        list($y2, $m2, $d2) = explode('-', $date2);
        $y = $m = $d = $_m = 0;
        $math = ($y2 - $y1) * 12 + $m2 - $m1; //相差总月数
        $y = round($math / 12);  //相差年数
        $m = intval($math % 12);  //相差月数
        $mm = $math; //相差总月数
        $d = (mktime(0, 0, 0, $m2, $d2, $y2) - mktime(0, 0, 0, $m2, $d1, $y2)) / 86400;
        if ($d < 0) {
            $m -= 1;
            $d += date('j', mktime(0, 0, 0, $m2, 0, $y2));
        }

        $m < 0 && $y -= 1;
        $str='';
        if($y>0){
            $str=$str.$y.'年';
        }
        if($m>0){
            $str=$str.$m.'月';
        }
        if($d>0){
            $str=$str.$d.'天';
        }
       return $str;
    }
}